<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Verify;
use Admin\Model\AdminModel;

/**
 * 后台登录控制器
 * Class LoginController
 * @package Admin\Controller
 */
class LoginController extends Controller{
    /**
     * 登录页面
     */
    public function index(){
//        echo md5('admin');
        $this->display();
    }

    /**
     * 生成验证码
     */
    public function verify(){
        $config = [
            'fontSize' => 30,
            'length'   => 4,
        ];
        $Verify = new Verify($config);
        $Verify->entry();
    }

    /**
     * 登录验证
     */
    public function login(){
        if(IS_AJAX){
            //判断验证码是否正确
            $verify = new \Think\Verify();
            if(!$verify->check(I('post.verify'))){
                $this->ajaxReturn(['info'=>'验证码不正确','status'=>101]);
            }

            $nam['username']=I('username');
            $nam=M("user_supplier")->where($nam)->find();
            $user = D('admin');
            $pwd=md5(md5(I('post.password')).$nam['salt']);
            $res = $user->checkUser(I('post.username'),$pwd);

            if(!$res){
                $this->ajaxReturn(['info'=>'用户名或密码错误','status'=>102]);
            }

            if($res['state']==3){
                $this->ajaxReturn(['info'=>'账号资料不全','status'=>103]);
            }elseif ($res['state']==2){
                $this->ajaxReturn(['info'=>'账号验证中','status'=>104]);
            }elseif ($res['state']==0){
                $this->ajaxReturn(['info'=>'已封号','status'=>105]);
            }
            //将登录成功的用户信息存入session
            session('supplier_id',$res['supplier_id']);
            session('username',$res['username']);

            //获取登录时间、IP
            $data['last_login_time'] = time();
            $data['last_login_ip'] = get_client_ip();
            $loginUser = M('user_supplier')->where(['supplier_id'=>$res['supplier_id']])->save($data);

            if($loginUser){
                $this->ajaxReturn(['info'=>'登录成功','status'=>200]);
            }
        }else{
            return '非法操作!';
        }
    }

    /**
     * 退出登录
     */
    public function logout(){
        session('supplier_id',null);
        session('username',null);

        $msg_log = APP_PATH.'log1.log';
        monitor_log($msg_log,'2222',FILE_APPEND);

//        $this->ajaxReturn(['info'=>'退出成功','status'=>200]);

        $this->redirect('Login/index','','1','退出成功');
    }
}